package com.wuzhishan.news.controller;

import com.wuzhishan.news.pojo.BlogArticle;
import com.wuzhishan.news.pojo.BlogUser;
import com.wuzhishan.news.service.apiService;
import com.wuzhishan.news.utils.EhcacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api")
public class ApiController {
    @Autowired
    private apiService apiService;

    /**
     * 热门用户
     * @return
     */
    @RequestMapping("hotusers.json")
    public List<BlogUser> hotusers(String maxResults){
        List<BlogUser> data = EhcacheUtil.get("Cache1","hotUsers");
        if(data == null || data.isEmpty()){
            data =  apiService.hotusers(maxResults);
            EhcacheUtil.put("Cache1","hotUsers",data,60,60);
        }
        return data;
    }
    /**
     * 最新文章
     * @return
     */
    @RequestMapping("latests.json")
    public List<BlogArticle> latests(String maxResults){
        List<BlogArticle> data = EhcacheUtil.get("Cache1","article_latests");
        if(data == null || data.isEmpty()){
           data =  apiService.latests(maxResults);
           EhcacheUtil.put("Cache1","article_latests",data,60,60);
        }
        return data;
    }

    /**
     * 热门文章
     * @return
     */
    @RequestMapping("hots.json")
    public List<BlogArticle> hots(String maxResults){
        System.out.println(maxResults);
        List<BlogArticle> data = EhcacheUtil.get("Cache1","article_hots");
        if(data == null || data.isEmpty()){
            System.out.println("发起SQL");
            data =  apiService.hots(maxResults);
            EhcacheUtil.put("Cache1","article_hots",data);
        }
        System.out.println("缓存命中");
        return data;
    }
    /**
     * 数据爬虫接口
     */
    @RequestMapping("/getArticle")
    public String getArticle(HttpSession session) throws IOException {
        apiService.getArticle(session);
        return null;
    }


}
